package mainControls;

import java.util.ArrayList;

import smallTools.SimpleTime;
import entities.Room;
import entities.Section;

public class RoomChecker {
	// room usage must be bigger than 50%
	private static final int SIZE_UPPER_BOUND_FACTOR = 2;
	private static final int SMALLEST_ROOM_SIZE = 30;

	private String allocatedRoomId;

	public String getAllocatedRoomId() {
		return allocatedRoomId;
	}

	public boolean check(Section theSection, SimpleTime startTimeCandidate) {
		// 1. Use the size of the section to find a room
		// 2. If find successful, store the room id and return true
		// 3. If find unsuccessfully, find a quota bigger than the size
		int size = theSection.getSectionSize();
		int sizeUpperBound = Math.max(SIZE_UPPER_BOUND_FACTOR * size,
				SMALLEST_ROOM_SIZE);
		int quota = size;
		int duration = theSection.getSectionDuration();
		while (quota <= sizeUpperBound) {
			ArrayList<Room> roomOfQuota = Room.getRoomsByQuota(quota);
			if (findOneInTheArray(startTimeCandidate, duration, roomOfQuota))
				return true;
			quota++;
		}

		return false;
	}

	private boolean findOneInTheArray(SimpleTime startTimeCandidate,
			int duration, ArrayList<Room> roomOfQuota) {
		if (roomOfQuota.isEmpty() == false) {
			for (Room rm : roomOfQuota) {
				if (checkRoomSchedule(rm, startTimeCandidate, duration) == true) {
					allocatedRoomId = rm.getRoomId();
					return true;
				}
			}
		}
		return false;
	}

	private boolean checkRoomSchedule(Room room, SimpleTime startTimeCandidate,
			int duration) {
		String[] relatedSectionIds = room.getRelatedSectionIds();
		for (String sectionId : relatedSectionIds) {
			Section now = Section.getSectionById(sectionId);
			if (now.getSectionStartTime() != null) {
				if (SimpleTime.areSectionsConflicted(now.getSectionStartTime(),
						now.getSectionDuration(), startTimeCandidate, duration))
					return false;
			}
		}
		return true;
	}
}
